/**
 * 通用内容工具函数
 * 支持文本文档、分镜脚本、数据采集等所有类型内容的处理
 */

import { 
  Content, 
  ContentType, 
  ContentStatus,
  BaseContent, 
  TextDocumentData, 
  StoryboardData, 
  StoryboardScene,
  DataCollectionData,
  AspectRatio,
  VideoResolution
} from '../types/document'

/**
 * 生成内容ID
 * 根据内容类型生成带前缀的唯一ID
 */
export const generateContentId = (type: ContentType): string => {
  const timestamp = Date.now().toString(36)
  const randomStr = Math.random().toString(36).substring(2, 8)
  
  const prefixMap = {
    [ContentType.TEXT_DOCUMENT]: 'text',
    [ContentType.STORYBOARD]: 'story',
    [ContentType.DATA_COLLECTION]: 'data'
  }
  
  return `${prefixMap[type]}_${timestamp}_${randomStr}`
}

/**
 * 生成内容摘要
 * 根据内容类型生成不同的摘要
 */
export const generateContentSummary = (content: Content): string => {
  switch (content.type) {
    case ContentType.TEXT_DOCUMENT:
      return generateTextDocumentSummary(content.data)
    case ContentType.STORYBOARD:
      return generateStoryboardSummary(content.data)
    case ContentType.DATA_COLLECTION:
      return generateDataCollectionSummary(content.data)
    default:
      return '暂无摘要'
  }
}

/**
 * 生成文本文档摘要
 */
export const generateTextDocumentSummary = (data: TextDocumentData): string => {
  if (!data.content || data.content.trim().length === 0) {
    return '空文档'
  }

  // 移除 Markdown 标记
  const plainText = data.content
    .replace(/[#*`_~\[\]()]/g, '')
    .replace(/\n+/g, ' ')
    .replace(/\s+/g, ' ')
    .trim()

  // 截取前100个字符
  return plainText.length > 100 
    ? plainText.substring(0, 100) + '...'
    : plainText
}

/**
 * 生成分镜脚本摘要
 */
export const generateStoryboardSummary = (data: StoryboardData): string => {
  const sceneCount = data.scenes.length
  const duration = formatDuration(data.totalDuration)
  const aspectRatio = data.videoFormat.aspectRatio
  
  return `${sceneCount}个场景，时长${duration}，格式${aspectRatio}`
}

/**
 * 生成数据采集任务摘要
 */
export const generateDataCollectionSummary = (data: DataCollectionData): string => {
  const taskTypeMap = {
    hot_topics: '热点监控',
    content_tracking: '内容追踪',
    competitor_analysis: '竞品分析'
  }
  
  const platformCount = data.targetPlatforms.length
  const progress = data.execution.progress || 0
  
  return `${taskTypeMap[data.taskType]}，${platformCount}个平台，进度${progress}%`
}

/**
 * 计算文本字数
 */
export const calculateWordCount = (content: string): number => {
  if (!content || content.trim().length === 0) {
    return 0
  }

  // 移除 Markdown 标记和多余空格
  const plainText = content
    .replace(/[#*`_~\[\]()]/g, '')
    .replace(/\s+/g, ' ')
    .trim()

  // 中英文混合计算：中文字符按1个字计算，英文单词按空格分隔计算
  const chineseChars = (plainText.match(/[\u4e00-\u9fa5]/g) || []).length
  const englishWords = plainText
    .replace(/[\u4e00-\u9fa5]/g, '')
    .trim()
    .split(/\s+/)
    .filter(word => word.length > 0).length

  return chineseChars + englishWords
}

/**
 * 计算分镜脚本总时长
 */
export const calculateStoryboardDuration = (scenes: StoryboardScene[]): number => {
  return scenes.reduce((total, scene) => {
    const duration = scene.timing?.duration || scene.duration || 0
    return total + duration
  }, 0)
}

/**
 * 格式化时长显示
 */
export const formatDuration = (seconds: number): string => {
  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  const secs = seconds % 60

  if (hours > 0) {
    return `${hours}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
  } else if (minutes > 0) {
    return `${minutes}:${secs.toString().padStart(2, '0')}`
  } else {
    return `${secs}秒`
  }
}

/**
 * 验证内容数据的通用函数
 */
export const validateContent = (content: Partial<Content>): string[] => {
  const errors: string[] = []

  // 基础字段验证
  if (!content.title || content.title.trim().length === 0) {
    errors.push('内容标题不能为空')
  }

  if (content.title && content.title.length > 200) {
    errors.push('内容标题不能超过200个字符')
  }

  if (!content.type || !Object.values(ContentType).includes(content.type)) {
    errors.push('内容类型无效')
  }

  // 类型特定验证
  if (content.type && content.data) {
    switch (content.type) {
      case ContentType.TEXT_DOCUMENT:
        errors.push(...validateTextDocumentData(content.data as TextDocumentData))
        break
      case ContentType.STORYBOARD:
        errors.push(...validateStoryboardData(content.data as StoryboardData))
        break
      case ContentType.DATA_COLLECTION:
        errors.push(...validateDataCollectionData(content.data as DataCollectionData))
        break
    }
  }

  return errors
}

/**
 * 验证文本文档数据
 */
export const validateTextDocumentData = (data: Partial<TextDocumentData>): string[] => {
  const errors: string[] = []

  if (data.content && data.content.length > 1000000) {
    errors.push('文档内容不能超过100万个字符')
  }

  if (data.wordCount && data.wordCount < 0) {
    errors.push('字数统计不能为负数')
  }

  return errors
}

/**
 * 验证分镜脚本数据
 */
export const validateStoryboardData = (data: Partial<StoryboardData>): string[] => {
  const errors: string[] = []

  if (data.scenes && data.scenes.length === 0) {
    errors.push('分镜脚本至少需要一个场景')
  }

  if (data.totalDuration && data.totalDuration < 0) {
    errors.push('总时长不能为负数')
  }

  if (data.videoFormat) {
    const validAspectRatios = ['16:9', '9:16', '1:1', '4:3']
    if (data.videoFormat.aspectRatio && !validAspectRatios.includes(data.videoFormat.aspectRatio)) {
      errors.push('无效的视频宽高比')
    }

    if (data.videoFormat.frameRate && (data.videoFormat.frameRate <= 0 || data.videoFormat.frameRate > 120)) {
      errors.push('帧率必须在1-120之间')
    }
  }

  // 验证场景数据
  if (data.scenes) {
    data.scenes.forEach((scene, index) => {
      if (!scene.title || scene.title.trim().length === 0) {
        errors.push(`第${index + 1}个场景的标题不能为空`)
      }
      
      const duration = scene.timing?.duration || scene.duration || 0
      if (duration < 0) {
        errors.push(`第${index + 1}个场景的时长不能为负数`)
      }
    })
  }

  return errors
}

/**
 * 验证数据采集任务数据
 */
export const validateDataCollectionData = (data: Partial<DataCollectionData>): string[] => {
  const errors: string[] = []

  const validTaskTypes = ['hot_topics', 'content_tracking', 'competitor_analysis']
  if (data.taskType && !validTaskTypes.includes(data.taskType)) {
    errors.push('无效的任务类型')
  }

  if (data.targetPlatforms && data.targetPlatforms.length === 0) {
    errors.push('至少需要选择一个目标平台')
  }

  if (data.config) {
    if (data.config.interval && data.config.interval <= 0) {
      errors.push('采集频率必须大于0')
    }

    if (data.config.limit && data.config.limit <= 0) {
      errors.push('采集数量限制必须大于0')
    }

    if (data.config.keywords && data.config.keywords.length === 0) {
      errors.push('至少需要一个关键词')
    }
  }

  return errors
}

/**
 * 创建空内容对象
 */
export const createEmptyContent = (
  type: ContentType, 
  title: string = '新内容'
): Content => {
  const now = new Date()
  const baseContent: BaseContent = {
    id: generateContentId(type),
    type,
    title,
    createdAt: now,
    updatedAt: now,
    status: ContentStatus.DRAFT,
    tags: [],
    metadata: {}
  }

  switch (type) {
    case ContentType.TEXT_DOCUMENT:
      return {
        ...baseContent,
        type: ContentType.TEXT_DOCUMENT,
        data: {
          content: '',
          wordCount: 0
        }
      } as Content

    case ContentType.STORYBOARD:
      return {
        ...baseContent,
        type: ContentType.STORYBOARD,
        data: {
          scenes: [],
          totalDuration: 0,
          videoFormat: {
            aspectRatio: AspectRatio.STANDARD,
            resolution: VideoResolution.FULL_HD,
            frameRate: 25
          },
          projectAssets: {
            characters: [],
            props: [],
            locations: [],
            music: [],
            soundEffects: []
          }
        }
      } as Content

    case ContentType.DATA_COLLECTION:
      return {
        ...baseContent,
        type: ContentType.DATA_COLLECTION,
        data: {
          taskType: 'hot_topics',
          targetPlatforms: [],
          config: {
            interval: 60,
            keywords: [],
            limit: 100,
            filters: {}
          },
          execution: {
            isRunning: false,
            progress: 0
          }
        }
      } as Content

    default:
      throw new Error(`不支持的内容类型: ${type}`)
  }
}

/**
 * 更新内容的修改时间
 */
export const updateContentTimestamp = (content: Content): Content => {
  return {
    ...content,
    updatedAt: new Date()
  }
}

/**
 * 内容状态转换辅助函数
 */
export const getStatusDisplayName = (status: ContentStatus): string => {
  const statusNames = {
    [ContentStatus.DRAFT]: '草稿',
    [ContentStatus.IN_PROGRESS]: '进行中',
    [ContentStatus.COMPLETED]: '已完成',
    [ContentStatus.PUBLISHED]: '已发布',
    [ContentStatus.ARCHIVED]: '已归档'
  }
  return statusNames[status] || '未知状态'
}

/**
 * 内容类型转换辅助函数
 */
export const getContentTypeDisplayName = (type: ContentType): string => {
  const typeNames = {
    [ContentType.TEXT_DOCUMENT]: '文本稿件',
    [ContentType.STORYBOARD]: '分镜脚本',
    [ContentType.DATA_COLLECTION]: '数据采集'
  }
  return typeNames[type] || '未知类型'
}

// 向后兼容的文档函数（保留原有接口）
export const generateDocumentId = (): string => generateContentId(ContentType.TEXT_DOCUMENT)
export const generateSummary = (content: string): string => generateTextDocumentSummary({ content, wordCount: 0 })
export const createEmptyDocument = (title: string = '新文档', content: string = ''): any => {
  const textContent = createEmptyContent(ContentType.TEXT_DOCUMENT, title)
  if (textContent.type === ContentType.TEXT_DOCUMENT) {
    textContent.data.content = content
    textContent.data.wordCount = calculateWordCount(content)
  }
  return textContent
}

export const validateDocument = (doc: any): string[] => validateContent(doc)